<template>
  <div v-cloak id="app-container">
    <div class="pageBody medicalCardAppointment">
      <div style="margin-top: 15px;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div style="display: inline-block;" class="title titleInfo">排班信息查询</div>
          <div>
            <el-button type="primary" size="medium" icon="el-icon-folder-opened" @click="excelExpectFn">导出</el-button>
          </div>
        </div>
      </div>
      <div class="medicalTableContainer">
        <el-form
          ref="formInline"
          :inline="true"
          :model="formInline"
          size="medium"
          style="margin-left: -40px;"
          label-width="110px"
          class="demo-form-inline">
          <el-row>
            <el-col :span="4-8">
              <el-form-item label="科室名称" style="width: 100%;" prop="departName">
                <el-input v-model="formInline.departName" style="width:100%" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="4-8">
              <el-form-item label="医生姓名" style="width: 100%;" prop="name">
                <el-input v-model="formInline.name" style="width:100%" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="4-8">
              <el-form-item label="出诊开始日期">
                <el-date-picker
                  v-model="formInline.date1"
                  :clearable="false"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4-8">
              <el-form-item label="出诊结束日期">
                <el-date-picker
                  v-model="formInline.date2"
                  :clearable="false"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width:  100%"
                  placeholder="选择日期"
                  default-time="23:59:59"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4-8">
              <el-form-item class="formItemBtn" style="width: 100%; padding-left: 40px;">
                <el-button type="primary" @click="onSubmit">查询</el-button>
                <el-button type="info" @click="resetForm('formInline')">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="tableContainer">
          <el-table
            ref="medicalTableData"
            :data="medicalTableData"
            :header-cell-style="headerCellStyle"
            style="width: 100%; overflow: auto;"
            height="100%"
          >
            <el-table-column min-width="200px" prop="DEPTNAME" show-overflow-tooltip label="科室名称">
              <template slot-scope="scope">
                <span>{{ scope.row.DEPTNAME ? scope.row.DEPTNAME : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="200px" prop="SPECIALITYNAME" show-overflow-tooltip label="专业名称">
              <template slot-scope="scope">
                <span>{{ scope.row.SPECIALITYNAME ? scope.row.SPECIALITYNAME : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="DOCTORNAME" min-width="120px" show-overflow-tooltip label="医生姓名">
              <template slot-scope="scope">
                <span>{{ scope.row.DOCTORNAME ? scope.row.DOCTORNAME : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="DOCTORDEGREE" min-width="120px" show-overflow-tooltip label="职称">
              <template slot-scope="scope">
                <span>{{ scope.row.DOCTORDEGREE ? scope.row.DOCTORDEGREE : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="DUTYDATE" min-width="100px" align="center" show-overflow-tooltip label="出诊日期">
              <template slot-scope="scope">
                <span>{{ scope.row.DUTYDATE ? scope.row.DUTYDATE : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="DUTYTIME" align="center" min-width="100px" show-overflow-tooltip label="出诊时段">
              <template slot-scope="scope">
                <span>{{
                  scope.row.DUTYTIME == 1 ? '上午' : scope.row.DUTYTIME == 2 ? '中午' : scope.row.DUTYTIME == 3 ? '下午' : '晚上'
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="SCHEDULEPRICE" min-width="80px" show-overflow-tooltip label="挂号费">
              <template slot-scope="scope">
                <span>{{ scope.row.SCHEDULEPRICE ? scope.row.SCHEDULEPRICE : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="SCHEDULETYPENAME" min-width="100px" show-overflow-tooltip label="挂号类型">
              <template slot-scope="scope">
                <span>{{ scope.row.SCHEDULETYPENAME ? scope.row.SCHEDULETYPENAME : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="AVAILABLEREGCOUNT"
              min-width="100px"
              align="center"
              show-overflow-tooltip
              label="可挂号数">
              <template slot-scope="scope">
                <span>{{ scope.row.AVAILABLEREGCOUNT ? scope.row.AVAILABLEREGCOUNT : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="AVAILABLEREGNUMBERS"
              align="center"
              min-width="100px"
              show-overflow-tooltip
              label="号签总数">
              <template slot-scope="scope">
                <span>{{ scope.row.AVAILABLEREGNUMBERS ? scope.row.AVAILABLEREGNUMBERS : '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="120">
              <template slot-scope="scope">
                <el-button
                  :disabled="scope.row.STATUS != 0"
                  style="font-size: 14px;padding: 0;"
                  type="text"
                  size="small"
                  @click.native.prevent="deleteRow(scope.$index, scope.row)">
                  停诊
                </el-button>
              </template>
            </el-table-column>

          </el-table>
        </div>
        <el-pagination
          :current-page="medicalCurrentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="medicalCurrentSize"
          :total="searchMedicalTotal"
          style="
            position: absolute;
            bottom: 3px;
            left: 7px;
            right: 0;
            padding: 5px 4px;
            background: #f6f6f7;
            z-index: 3;
            margin: 0 20px;
          "
          background
          layout=" prev, pager, next, jumper, total, sizes"
          @size-change="medicalSizeChange"
          @current-change="medicalCurrentChange"
        />
      </div>
    </div>
    <!-- 确认 -->
    <el-dialog
      :visible.sync="giveUpRegistration"
      custom-class="selfDialog"
      title="提示"
      width="460px"
      @closed="loadingList.stopClinic = false"
    >
      <div
        style="
            padding: 20px 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-family: 'SourceHanSansCN Regular';
          "
      >
        <div
          style="
              font-size: 16px;
              color: #031223;
              font-weight: bold;
              margin-bottom: 10px;
            "
        >
          确定要停诊吗？
        </div>
        <div style="color: #666a6f; font-size: 14px">
          停诊后数据将不可恢复，请谨慎操作！
        </div>
      </div>
      <span slot="footer" style="text-align: center" class="dialog-footer">
        <el-button
          :loading="loadingList.stopClinic"
          size="medium"
          type="primary"
          @click="giveUpRegFn"
        >确定</el-button
        >
        <el-button
          size="medium"
          type="info"
          @click="giveUpRegistration = false"
        >取消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<style>
[v-cloak] {
  display: none;
}
</style>
<script>
import axios from 'axios'

export default {
// var app = new Vue({
//   name: 'App',
  directives: {
    scroll: {
      // 指令的定义
      bind: function(el, binding) {
        const scrollDom = el.querySelector(
          '.el-select-dropdown .el-select-dropdown__wrap'
        )
        scrollDom.addEventListener('scroll', function() {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    return {
      url: '${ctxPath}/yq-hospital/webcall?action=',
      url2: '${ctxPath}/yq-hospital/servlet/deptWork?action=',
      url3: '${ctxPath}/yq-hospital/servlet/userSchedule?action=',
      // url: "/yq-hospital/webcall?action=",
      // url2:'/yq-hospital/servlet/deptWork?action=',
      // url3:'/yq-hospital/servlet/userSchedule?action=',
      hospitalNo: 'SYY01', // 医院编号
      medicalTableData: [],
      formInline: {
        name: '',
        departName: '',
        date1: '',
        date2: '',
        uploadLogId: '${param.uploadLogId}'
      },
      giveUpRegistration: false,
      hospitalMedicalPageIndex: 1,
      hospitalMedicalPageSize: 10,
      headerCellStyle: {
        backgroundColor: '#f6f6f7',
        color: '#3b3e41',
        fontSize: '15px'
      },
      loadingList: {
        stopClinic: false
      },

      medicalCurrentPage: 1,
      medicalCurrentSize: 10,
      searchMedicalTotal: 0,
      dialogFormVisible: false,
      clinicData: {}
    }
  },
  mounted: function() {
    var that = this
    this.formInline.date1 = this.today()
    // this.formInline.date1 = '2023-07-13 00:00:00'
    this.formInline.date2 = this.monthTime()

    // this.formInline.date3 = this.today()
    // this.formInline.date4 = this.monthTime()
    // this.appClickFn();
    var isFn = false
    var bc = new BroadcastChannel('yqCast')
    var sendData = ''
    bc.onmessage = function(e) {
      sendData = e.data
      that.formInline.uploadLogId = sendData.ID
      that.formInline.name = ''
      that.formInline.departName = ''
      that.formInline.date1 = sendData.date1
      that.formInline.date2 = sendData.date2
      that.getWorkInfoByDeptNo()
      console.log('[BroadcastChannel] receive message:', sendData)
      if (sendData.ID) isFn = true
    }
    setTimeout(() => {
      if (!isFn) that.getWorkInfoByDeptNo()
    }, 200)
  },
  methods: {
    // 请求数据封装函数
    request(action, data, callback, type) {
      var that = this
      var url
      if (type) {
        url = this.url2
      } else {
        url = this.url
      }
      var param = {
        data: JSON.stringify(data)
      }
      axios
        .post(url + action, param, {
          headers: {
            'Content-Type':
              'application/x-www-form-urlencoded;charset=UTF-8'
          }
        })
        .then(function(response) {
          console.log('响应回来的数据', response.data)
          var state = response.data.state

          callback(response.data, state)

          // for (var key in that.loadingList) {
          //   // console.log("key", key);
          //   that.loadingList[key] = false;
          // }
        })
        .catch(function(error) {
          // console.log(error, 120);
          that.$message.error(error)
          // for (var key in that.loadingList) {
          //   // console.log("key", key);
          //   that.loadingList[key] = false;
          // }
        })
    },
    serializeObject(obj, prefix) {
      var serializedData = ''

      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          var prop = prefix ? prefix + '[' + key + ']' : key
          var value = obj[key]

          if (typeof value === 'object') {
            // 如果属性值是对象，则递归处理
            serializedData += serializeObject(value, prop)
          } else {
            // 否则，将属性和值进行编码
            serializedData += encodeURIComponent(prop) + '=' + encodeURIComponent(value) + '&'
          }
        }
      }

      // 去除末尾的 '&' 符号
      serializedData = serializedData.slice(0, -1)

      return serializedData
    },
    onSubmit() {
      console.log('submit!')
      this.formInline.uploadLogId = ''
      this.medicalCurrentPage = 1
      this.getWorkInfoByDeptNo()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.formInline.date1 = this.today()
      this.formInline.date2 = this.monthTime()
    },
    getWorkInfoByDeptNo() {
      var that = this
      this.request(
        'deptWorkDao.getWorkInfoByDeptNo',
        {
          pageIndex: this.medicalCurrentPage,
          pageSize: this.medicalCurrentSize,
          pageType: '3',
          // hospitalNo: this.hospitalNo,
          doctorName: this.formInline.name,
          deptName: this.formInline.departName,
          dutyBdate: this.formInline.date1,
          dutyEdate: this.formInline.date2,
          uploadLogId: this.formInline.uploadLogId
        },
        function(res) {
          console.log('res', res)
          if (res.state == '1') {
            that.medicalTableData = res.data
            that.searchMedicalTotal = res.totalRow
          } else {
            that.$message.error(res.msg)
            that.medicalTableData = []
            that.searchMedicalTotal = 0
          }
          // this.$refs.upload.clearFiles()
        })
    },
    deleteRow(index, row) {
      // rows.splice(index, 1);
      this.clinicData = row
      console.log(row)
      this.giveUpRegistration = true
    },
    delRowData(data) {
      this.request(
        'del',
        data,
        (data, state) => {
          console.log('删除', data)
          if (state == '1' || state == '0') {
            this.$message.success(data.msg)
          } else {
            this.$message.error(data.msg)
          }
        },
        '2'
      )
    },
    handleStateFn(state) {
      var result = ''
      switch (state) {
        case '0':
          result = '正常'
          break
        case '1':
          result = '电话取消'
          break
        case '2':
          result = '待停诊'
          break
        case '3':
          result = '已停诊'
          break
        case '4':
          result = '已取号'
          break
        case '5':
          result = '超时违约'
          break
        case '6':
          result = '现场取消'
          break
        case '7':
          result = '已换诊'
          break
        case '8':
          result = '手机终端挂号'
          break
        case '9':
          result = '手机终端取消'
          break
        case '10':
          result = '手机终端挂号,114取消'
          break
        case '11':
          result = 'IVR流程挂号'
          break
        case '12':
          result = '停诊（未取号）'
          break
        case '13':
          result = '停诊（已取号）'
          break
        case '14':
          result = '换诊取消'
          break
        case '15':
          result = '换诊预约（未取号）'
          break
        case '16':
          result = '换诊预约（已取号）'
          break
        case '-1':
          result = '失败'
          break
      }
      return result
    },
    // 确定停诊
    giveUpRegFn() {
      this.stopWorkInfo()
    },
    stopWorkInfo() {
      console.log(this.clinicData) // 停诊数据
      this.loadingList.stopClinic = true
      this.request('stopWorkInfo', {
        // hospitalNo: this.hospitalNo,
        workId: this.clinicData.WORKID
      }, (data, state) => {
        console.log('停诊数据', data)
        if (state == '1' || state == '0') {
          this.$message.success(data.msg)
          // 请求表格数据
          this.getWorkInfoByDeptNo()
        } else {
          this.$message.error(data.msg)
          // this.loadingList.stopClinic = false
        }
        this.giveUpRegistration = false
      }, 'servlet')
    },
    medicalSizeChange(val) {
      this.medicalCurrentSize = val
      this.getWorkInfoByDeptNo()
      // console.log(`每页 ${val} 条`);
    },
    medicalCurrentChange(val) {
      this.medicalCurrentPage = val
      this.getWorkInfoByDeptNo()
      // console.log(`当前页: ${val}`);
    },
    excelExpectFn() {
      var data = {
        // hospitalNo: this.hospitalNo,
        doctorName: this.formInline.name,
        deptName: this.formInline.departName,
        dutyBdate: this.formInline.date1,
        dutyEdate: this.formInline.date2,
        uploadLogId: this.formInline.uploadLogId
      }
      console.log(encodeURIComponent(JSON.stringify(data)))
      var param = encodeURIComponent(JSON.stringify(data))
      location.href = this.url2 + 'exportWorkInfo&data=' + param
    },
    today() {
      // debugger;
      // 获取当天日期
      var today = new Date()
      // 获取明天日期
      // var today = new Date(today);
      // 格式化日期为 yyyy-MM-dd 格式
      var year = today.getFullYear()
      var month = (today.getMonth() + 1).toString().padStart(2, '0')
      var day = today.getDate().toString().padStart(2, '0')
      var hours = today.getHours().toString().padStart(2, '0')
      var minutes = today.getMinutes().toString().padStart(2, '0')
      var seconds = today.getSeconds().toString().padStart(2, '0')
      return year + '-' + month + '-' + day
    },
    monthTime() {
      // 获取当天日期
      const today = new Date()
      // 获取16天后的日期
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 30)
      // 格式化日期为 yyyy-MM-dd 格式
      const year = tomorrow.getFullYear()
      const month = (tomorrow.getMonth() + 1).toString().padStart(2, '0')
      const day = tomorrow.getDate().toString().padStart(2, '0')
      const hours = tomorrow.getHours().toString().padStart(2, '0')
      const minutes = tomorrow.getMinutes().toString().padStart(2, '0')
      const seconds = tomorrow.getSeconds().toString().padStart(2, '0')
      return year + '-' + month + '-' + day
    },
    appClickFn() {
      var that = this
      window.addEventListener('keydown', function(e) {
        console.log('e.keyCode', e.keyCode)

        if (that.activePageIndex == 1) {
          // 医院科室信息
          if (that.isTableClick) {
            var dataLength = that.tableData.length - 1
            if (e.keyCode == 38) {
              // 上键
              // console.log(1);
              if (that.tableSelectIndex > 0) {
                that.tableSelectIndex--
                // console.log(that.tableSelectIndex);
                that.$refs.singleTable.setCurrentRow(
                  that.tableData[that.tableSelectIndex]
                )
              }
            } else if (e.keyCode == 40) {
              // 下键
              // console.log(2);
              if (that.tableSelectIndex < dataLength) {
                that.tableSelectIndex++
                // console.log(that.tableSelectIndex);
                that.$refs.singleTable.setCurrentRow(
                  that.tableData[that.tableSelectIndex]
                )
              }
            }
          }
          if (e.keyCode == 32) {
            // 空格
            e.preventDefault()
            // console.log(that.$refs.registrationBtn.$el)
            if (that.$refs.registrationBtn) {
              that.$refs.registrationBtn.$el.click()
            } else {
              that.$message.error('暂无号源，无法挂号！')
            }
          } else if (e.keyCode == 13) { // 回车
            if (document.activeElement.tagName.toLowerCase() !== 'input' && document.activeElement.tagName.toLowerCase() !== 'button') {
              that.onSubmit2()
            }
          }
        } else if (that.activePageIndex == 2) {
          // 受理挂号业务
          // console.log(document.activeElement.tagName.toLowerCase());
          if (e.keyCode == 13) {
            // 回车
            if (document.activeElement.tagName.toLowerCase() !== 'input') {
              e.preventDefault()
              // console.log(that.giveUpVisible);
              if (that.giveUpVisible) {
                // that.giveUpOper(); // 放弃挂号
              } else {
                that.$refs.getUserInfo.$el.click()
                // that.getCheckUserInfo(); // 调用查询用户
              }
            }
          } else if (e.keyCode == 9) {
            // tab
            // e.preventDefault();
          } else if (e.keyCode == 27) {
            // esc
            e.preventDefault()
            // console.log(that.$refs.selfDialog.$el)
            const computedStyle = window.getComputedStyle(
              that.$refs.selfDialog.$el
            )
            if (computedStyle.display === 'none') {
              that.giveUpVisible = true
            }
          } else if (e.keyCode == 32) {
            // 空格
            // if (document.activeElement.tagName.toLowerCase() !== "input") {
            //   e.preventDefault();
            //   that.submitForm("ruleForm");
            // }
            var messageDom = document.querySelector(
              '.el-message-box__wrapper'
            )
            // console.log(messageDom);
            if (messageDom) { var styleList = window.getComputedStyle(messageDom) }
            var activeTagName =
              document.activeElement.tagName.toLowerCase()
            if (
              activeTagName !== 'input' &&
              (!messageDom || styleList.display === 'none') &&
              !that.giveUpVisible
            ) {
              e.preventDefault()
              that.submitForm('ruleForm')
            }
            if (that.giveUpVisible) {
              that.giveUpOper() // 放弃支付
            }
          }
        } else if (that.activePageIndex == 3) {
          if (e.keyCode == 32) {
            // 空格
            var messageDom = document.querySelector(
              '.el-message-box__wrapper'
            )
            // console.log(messageDom);
            if (messageDom) { var styleList = window.getComputedStyle(messageDom) }
            var activeTagName =
              document.activeElement.tagName.toLowerCase()
            if (
              activeTagName !== 'input' &&
              (!messageDom || styleList.display === 'none') &&
              !that.giveUpVisible
            ) {
              e.preventDefault()
              that.submitPayForm('PayRuleForm')
            }
            if (that.giveUpVisible) {
              that.giveUpOper() // 放弃支付
            }
          } else if (e.keyCode == 27) {
            // esc
            e.preventDefault()
            // console.log(that.$refs.selfDialog.$el)
            var messageDom = document.querySelector(
              '.el-message-box__wrapper'
            )
            if (messageDom) { var styleList = window.getComputedStyle(messageDom) }
            var computedStyle = window.getComputedStyle(
              that.$refs.selfDialog.$el
            )
            if (
              computedStyle.display === 'none' &&
              (!messageDom || styleList.display === 'none')
            ) {
              that.giveUpVisible = true
            }
          } else if (e.keyCode == 13) {
            // 回车
            if (document.activeElement.tagName.toLowerCase() !== 'input') {
              e.preventDefault()
            }
          }
        }
      })
    },
    openEditDialog() {
    },
    closeEditDialog() {
    }
  }
}
</script>
